/*
 * Copyright (c) 2011, All Rights Reserved
 * 
 * LocaleChnageInterceptor.java
 * Modification History
 * *************************************************************
 * Date				Author			Comment
 * 23042011			venky			Created
 * *************************************************************
 */
package my.project.builder.support;

import java.util.List;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import my.project.builder.AppConstants;
import my.project.builder.dto.LookupDTO;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.propertyeditors.LocaleEditor;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;

/**
 * LocaleChangeInterceptor helper class
 * 
 * @author venky
 *
 */
public class LocaleChangeInterceptor extends
		org.springframework.web.servlet.i18n.LocaleChangeInterceptor
{
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler)
			throws ServletException
	{
		if (super.preHandle(request, response, handler))

		{
			LocaleResolver localeResolver = RequestContextUtils
					.getLocaleResolver(request);
			
			Locale locale = localeResolver.resolveLocale(request);
			
			if (localeResolver != null && locale != null)
			{
				String language = locale.getLanguage();
				String country = locale.getCountry();
				
				if(!StringUtils.isBlank(country))
				{
					language += "_" + country;
				}
				
				List<LookupDTO> langList = null;
				boolean validLanguage = false;
				if(langList != null)
				{
					for(LookupDTO dto :langList)
					{
						if(StringUtils.equals(dto.getCode(),language))
						{
							validLanguage = true;
							break;
						}
					}
				}
				
				if(!validLanguage)
				{
					language = "en_US";
					localeResolver.setLocale(request, response, Locale.US);
					locale = localeResolver.resolveLocale(request);
					
					LocaleEditor editor = new LocaleEditor();
					editor.setAsText("en");
					localeResolver.setLocale(request, response, (Locale)editor.getValue());
				}
				
				request.getSession().setAttribute(AppConstants.SESS_LANGUAGE, language);
				request.getSession().setAttribute(AppConstants.SESS_LOCALE, locale);
			}
			return true;
		}
		return false;
	}
}
